package com.wxtt.android.recyclerview;

import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.fast.dev.frame.Adapter.recycleview.FastAdapter;
import com.fast.dev.frame.Adapter.recycleview.IItem;
import com.fast.dev.frame.Adapter.recycleview.adapter.HeaderAdapter;
import com.fast.dev.frame.Adapter.recycleview.adapter.ItemAdapter;
import com.fast.dev.frame.Adapter.recycleview.stickyheader.StickyRecyclerHeadersDecoration;
import com.wxtt.android.adapter.StickyHeaderAdapter;
import com.wxtt.android.item.SampleItem;

import java.util.ArrayList;
import java.util.List;

/**
 * 说明：StickyHeaderView
 * <p/>
 * 作者：fanly
 * <p/>
 * 时间：2016/1/24 0:46
 * <p/>
 * 版本：verson 1.0
 */
public class StickyHeaderView {

    private static final String[] headers = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

    private FastAdapter fastAdapter;
    private RecyclerView recyclerView;
    private StickyHeaderAdapter stickyHeaderAdapter;
    private HeaderAdapter headerAdapter;
    private ItemAdapter itemAdapter;

    private Bundle savedInstanceState;

    public StickyHeaderView(RecyclerView recyclerView,Bundle savedInstanceState){
        this.recyclerView = recyclerView;
        this.savedInstanceState = savedInstanceState;
        initAdapter();
        initRecyclerView();
    }

    private void initRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(stickyHeaderAdapter.wrap(itemAdapter.wrap(headerAdapter.wrap(fastAdapter))));
        headerAdapter.add(new SampleItem().withName("Header").withIdentifier(1));
        List<IItem> items = new ArrayList<>();
        for (int i = 1; i <= 100; i++) {
            items.add(new SampleItem().withName("Test " + i).withHeader(headers[i / 5]).withIdentifier(100 + i));
        }
        itemAdapter.add(items);

        final StickyRecyclerHeadersDecoration decoration = new StickyRecyclerHeadersDecoration(stickyHeaderAdapter);

        stickyHeaderAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                decoration.invalidateHeaders();
            }
        });

        recyclerView.addItemDecoration(decoration);


        fastAdapter.withSavedInstanceState(savedInstanceState);
    }

    private void initAdapter(){
        fastAdapter = new FastAdapter();
        stickyHeaderAdapter = new StickyHeaderAdapter();
        headerAdapter = new HeaderAdapter();
        itemAdapter = new ItemAdapter();
    }

}
